package com.hsmw.api.controller.forman;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.mapper.*;
import com.hsmw.api.payment.*;
import com.hsmw.api.service.HsmwInviteRecordService;
import com.hsmw.api.service.HsmwPaymentRecordService;
import com.hsmw.api.service.HsmwRechargeRecordService;
import com.hsmw.api.vo.PayInfo;
import com.hsmw.api.vo.PaymentVO;
import com.hsmw.api.vo.QueryPayInfo;
import com.hsmw.api.vo.UniPayInfo;
import com.hsmw.common.base.BasePage;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.DateUtils;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.hsmw.common.base.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.FAIL;
import static com.htn.common.core.constant.CommonConstants.ResponseStatus.SUCCESS;

/**
 * <p>
 * 充值记录表 前端控制器
 * </p>
 *
 * @author wd
 * @since 2021-11-23
 */
@RestController
@RequestMapping("/api/payment")
@Api(tags = "支付接口")
public class HsmwPaymentRecordController extends BaseController<HsmwPaymentRecordService, HsmwPaymentRecord> {

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;

    @Autowired
    private HsmwLeasingCompanyMapper hsmwLeasingCompanyMapper;


    @Autowired
    private HsmwPaymentRecordService hsmwPaymentRecordService;


    @Autowired
    private HsmwPaymentRecordMapper hsmwPaymentRecordMapper;

    @Autowired
    private HsmwSysParamMapper hsmwSysParamMapper;




    //获取登录用户下所有客户
    private static final String clientrUrl = "https://qr.chinaums.com/netpay-route-server/api/";

    //获取登录用户下所有客户
    private static final String unipayClientrUrl = "https://gateway.95516.com/gateway/api/appTransReq.do";




    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");




    @ApiOperation(value = "新增充值信息 ",notes = "新增充值信息",produces = "application/json")
    @PostMapping("/saveOrUpdatePayMentInfo")
    public DataResponse saveOrUpdateRechargeInfo(@RequestBody HsmwPaymentRecord record){
        HsmwHtnUser user = currentHsmwUserUtils.getCurrentHtnUserInfo();
        record.setCompanyId(user.getOwnCompanyId());
        record.setUserType(user.getType());
        record.setCompanyName(user.getOwnCompanyName());
        record.setPayTime(LocalDateTime.now());
        record.setRechargeUserId(user.getId());
        record.setStatus(RechargeStatusEnum.ON_PROCESS.getValue());
        record.setCreateUser(user.getId());
        record.setRechargeUserName(user.getName());
        record.setPayType(PayTypeEnum.TO_PUB.getValue());
        hsmwPaymentRecordService.save(record);
        return  new DataResponse();
    }


    @ApiOperation(value = "修改充值信息状态 必传 id,  status  1. 未入账 2. 已入账 3. 充值失败-退回 ",notes = "修改充值信息",produces = "application/json")
    @PostMapping("/updateRechargeStatus")
    public DataResponse reInviteInfo(@RequestBody HsmwPaymentRecord record){
        if(StringUtils.isBlank(record.getId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"充值信息ID为空，请重新输入");
        }
        if(StringUtils.isBlank(record.getStatus())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"充值信息状态为空，请重新输入");
        }
        try {
            LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
            record.setUpdateTime(LocalDateTime.now());
            record.setHandleUserId(user.getId());
            record.setHandleUserName(user.getUsername());
            hsmwPaymentRecordService.updateById(record);
            //如果是中控确认充值成功 那么 将公司的或者搅拌站的额度更新一下。、
            if(RechargeStatusEnum.SUCCESS.getValue().equals(record.getStatus())){
                HsmwPaymentRecord rechargeRecord = hsmwPaymentRecordService.getById(record.getId());
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(rechargeRecord.getUserType())){
                    HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(rechargeRecord.getCompanyId());
                    if(StringUtils.isNull(plantInfo.getAvailableLimit())){
                        plantInfo.setAvailableLimit(new BigDecimal(0.00));
                    }
                    plantInfo.setAvailableLimit(plantInfo.getAvailableLimit().add(new BigDecimal(rechargeRecord.getPayAmount())));
                    hsmwConcretePlantInfoMapper.updateById(plantInfo);
                }
                if(HtnUserTypeEnum.COMPANY.getValue().equals(rechargeRecord.getUserType())){
                    HsmwLeasingCompany  company = hsmwLeasingCompanyMapper.selectById(rechargeRecord.getCompanyId());
                    company.setAvailableLimit(company.getAvailableLimit().add(new BigDecimal(rechargeRecord.getPayAmount())));
                    hsmwLeasingCompanyMapper.updateById(company);
                }
                hsmwPaymentRecordService.updateById(rechargeRecord);
            }
            return  new DataResponse(SUCCESS,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"修改充值信息状态失败，请联系管理员！");
        }
    }

    @ApiOperation(value = "混天凝app 查询充值信息 ",notes = "查询充值信息",produces = "application/json")
    @PostMapping("/queryPaymentInfo")
    public DataResponse queryRechargeInfo(@RequestBody @Valid BasePage<HsmwPaymentRecord> basePage){
        try {
            IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
            HsmwPaymentRecord hsmwPaymentRecord = basePage.getRequestData();
            if(StringUtils.isNull(hsmwPaymentRecord)){
                hsmwPaymentRecord =new HsmwPaymentRecord();
            }
            HsmwHtnUser hsmwHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            hsmwPaymentRecord.setCompanyId(hsmwHtnUser.getOwnCompanyId());
            IPage<HsmwPaymentRecord> rechargeRecordList  =hsmwPaymentRecordService.selectpageList(page,hsmwPaymentRecord);
            return  new DataResponse(SUCCESS,rechargeRecordList);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询充值信息失败，请联系管理员！");
        }
    }

    @ApiOperation(value = "中控查询充值信息  rechargeStatus   0. 未入账 1. 已入账 2. 充值失败-退回 3.超时   不传默认全部",notes = "中控查询充值信息",produces = "application/json")
    @PostMapping("/queryAllPayInfo")
    public DataResponse queryAllRechargeInfo(@RequestBody @Valid BasePage<HsmwPaymentRecord> basePage){
        try {
            IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
            HsmwPaymentRecord hsmwPaymentRecord = basePage.getRequestData();
            if(StringUtils.isNull(hsmwPaymentRecord)){
                hsmwPaymentRecord =new HsmwPaymentRecord();
            }
            IPage<HsmwPaymentRecord> rechargeRecordList  =hsmwPaymentRecordService.selectpageList(page,hsmwPaymentRecord);
            return  new DataResponse(SUCCESS,rechargeRecordList);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询充值信息失败，请联系管理员！");
        }
    }



    @ApiOperation(value = "微信 支付宝支付", notes = "微信 支付宝", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "txnAmt", value = "金额", dataType = "String", required = true),
            @ApiImplicitParam(name = "type", value = "微信（app跳转小程序支付）wx.appPreOrder,微信（直连）wx.unifiedOrder,支付宝（支付宝跳转小程序支付）trade.appPreOrder,支付宝trade.precreate,全民付 qmf.order,银联云闪付（走银联全渠道）uac.appOrder,ApplePay支付applepay.order ", dataType = "String", required = true)
    })
    @PostMapping("/pay")
    public DataResponse pay(Long txnAmt,String type) {

        HsmwSysParam hsmwSysParam = hsmwSysParamMapper.selectOne(new LambdaQueryWrapper<HsmwSysParam>().eq(HsmwSysParam::getId,"1").eq(HsmwSysParam::getStatus,"0"));
        PaymentVO paymentVO = new PaymentVO();
        HashMap<String, String> paramsMap = new HashMap<>();
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String orderId = DemoBase.getOrderId();
        MessageDigest messageDigest;
        String encodeStr = "";
        PayInfo payInfo = new PayInfo();
        payInfo.setInstMid("APPDEFAULT");
        payInfo.setMerOrderId("134Z"+orderId);
        payInfo.setMid("89812007392ARVV");
        payInfo.setMsgSrc("WWW.HTN.COM");
        payInfo.setMsgType(type);
        payInfo.setNotifyUrl(hsmwSysParam.getParam());
        payInfo.setRequestTimestamp(format);
        payInfo.setSignType("SHA256");
        payInfo.setTid("01599633");
        payInfo.setTotalAmount(txnAmt);
        if (type.startsWith("wx.")){
            payInfo.setSubAppId("wx0976523f3c8ccf01");
            payInfo.setTradeType("APP");
            paramsMap.put("tradeType","APP");
            paramsMap.put("subAppId","wx0976523f3c8ccf01");
        }
        String s = null;
        paramsMap.put("merOrderId","134Z"+orderId);
        paramsMap.put("mid","89812007392ARVV");
        paramsMap.put("msgSrc","WWW.HTN.COM");
        paramsMap.put("msgType",type);
        paramsMap.put("requestTimestamp",format);
        paramsMap.put("signType","SHA256");//
        paramsMap.put("tid","01599633");
        paramsMap.put("totalAmount",String.valueOf(txnAmt));
        paramsMap.put("notifyUrl",hsmwSysParam.getParam());
        paramsMap.put("instMid","APPDEFAULT");

        if(type.equals("wx.appPreOrder")){
            s = payInfo.toWXString() + "aaBn6GEBPdiRtDCWNaa5h2RpGbZfbB4FXndAj6mjeC6C2HCn";
        }else {
            s = payInfo.toString() + "aaBn6GEBPdiRtDCWNaa5h2RpGbZfbB4FXndAj6mjeC6C2HCn";
        }
        System.err.println(s);
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(s.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.err.println("encodeStr------"+encodeStr);
        paramsMap.put("sign",encodeStr);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        cn.hutool.json.JSONObject json = JSONUtil.parseFromMap(paramsMap);
        System.err.println("json-----"+json);
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, json.toString());
        Request request = new Request.Builder()
                .url(clientrUrl)
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            cn.hutool.json.JSONObject responses = JSONUtil.parseObj(response.body().string());
            System.err.println("responses----------"+responses);
            if(responses == null || responses.getStr("errCode").equals("BAD_REQUEST")){
                return new DataResponse(FAIL,"验签失败");
            }
            paymentVO = JSONUtil.toBean(responses, PaymentVO.class);
            HsmwPaymentRecord hsmwPaymentRecord = new HsmwPaymentRecord();
            hsmwPaymentRecord.setPayAmount(txnAmt);
            hsmwPaymentRecord.setPayTime(LocalDateTime.now());
            hsmwPaymentRecord.setOrderId(paramsMap.get("merOrderId"));
            hsmwPaymentRecord.setStatus(RechargeStatusEnum.ON_PROCESS.getValue());
//            hsmwPaymentRecord.setTransactionNumber(paymentVO.getAppPayRequest().getTn());
            hsmwPaymentRecord.setSign(encodeStr);
            hsmwPaymentRecord.setType(type);
            if (type.startsWith("wx.")){
                hsmwPaymentRecord.setPayType(PayTypeEnum.WX.getValue());
            }
            if (type.startsWith("trade.")){
                hsmwPaymentRecord.setPayType(PayTypeEnum.ALIPAY.getValue());
            }
            if (type.startsWith("uac.")){
                hsmwPaymentRecord.setPayType(PayTypeEnum.UNIPAY.getValue());
            }
            HsmwHtnUser user = currentHsmwUserUtils.getCurrentHtnUserInfo();
            hsmwPaymentRecord.setCompanyId(user.getOwnCompanyId());
            hsmwPaymentRecord.setUserType(user.getType());
            hsmwPaymentRecord.setCompanyName(user.getOwnCompanyName());
            hsmwPaymentRecord.setRechargeUserId(user.getId());
            hsmwPaymentRecord.setRechargeUserName(user.getName());
            hsmwPaymentRecord.setCreateUser(user.getId());
            hsmwPaymentRecordMapper.insert(hsmwPaymentRecord);
            return new DataResponse(paymentVO);

        } catch (IOException e) {
            e.printStackTrace();
            return new DataResponse(paymentVO);
        }
    }


    @ApiOperation(value = "银联支付", notes = "银联支付", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "txnAmt", value = "金额", dataType = "Long", required = true),
            @ApiImplicitParam(name = "type", value = "微信（app跳转小程序支付）wx.appPreOrder,微信（直连）wx.unifiedOrder,支付宝（支付宝跳转小程序支付）trade.appPreOrder,支付宝trade.precreate,全民付 qmf.order,银联云闪付（走银联全渠道）uac.appOrder,ApplePay支付applepay.order ", dataType = "String", required = true)
    })
    @PostMapping("/unipay")
    public DataResponse unipay(Long txnAmt, String type) {

        String merOrderId = DemoBase.getOrderId();
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        Map<String, String> contentData =new HashMap();
        contentData.put("version", SDKConfig.getConfig().getVersion());              //版本号，全渠道默认值
        contentData.put("encoding", "UTF-8");              //字符集编码，可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", "01");                        //交易类型 01:消费
        contentData.put("txnSubType", "01");                    //交易子类 01：消费
        contentData.put("bizType", "000201");                    //填写000201
        contentData.put("channelType", "08");                    //渠道类型 08手机
        //***商户接入参数***//*
        contentData.put("merId", "89812007392ARWA");      //商户号码，请改成自己申请的正式商户号或者open上注册得来的777测试商户号
        contentData.put("accessType", "0");                          //接入类型，商户接入填0 ，不需修改（0：直连商户， 1： 收单机构 2：平台商户）
        contentData.put("orderId", merOrderId);             //商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则
        contentData.put("txnTime", format);        //订单发送时间，取系统时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
        contentData.put("currencyCode", "156");                      //交易币种（境内商户一般是156 人民币）
        contentData.put("txnAmt", String.valueOf(txnAmt));
        contentData.put("backUrl", SDKConfig.getConfig().getBackUrl());
        //contentData.put("accNo", "6217002340022626891");                            			 //
        Map<String, String> reqData = AcpService.sign(contentData,DemoBase.encoding);
        System.err.println("reqdata:"+reqData.toString());//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String requestAppUrl = SDKConfig.getConfig().getAppRequestUrl();				 			   //交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.backTransUrl
        Map<String, String> rspData = AcpService.post(reqData,requestAppUrl,DemoBase.encoding);
        System.err.println("reseponse: "+rspData.toString());
        //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过
        if(!rspData.isEmpty()){
            if(AcpService.validate(rspData, DemoBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode") ;
                if(("00").equals(respCode)){

                    HsmwPaymentRecord hsmwPaymentRecord = new HsmwPaymentRecord();
                    hsmwPaymentRecord.setPayAmount(txnAmt);
                    hsmwPaymentRecord.setPayTime(LocalDateTime.now());
                    hsmwPaymentRecord.setOrderId(contentData.get("orderId"));
                    hsmwPaymentRecord.setStatus(RechargeStatusEnum.ON_PROCESS.getValue());
//            hsmwPaymentRecord.setTransactionNumber(paymentVO.getAppPayRequest().getTn());
                    hsmwPaymentRecord.setTransactionNumber(rspData.get("tn"));
                    hsmwPaymentRecord.setType(type);
                    if (type.startsWith("wx.")){
                        hsmwPaymentRecord.setPayType(PayTypeEnum.WX.getValue());
                    }
                    if (type.startsWith("trade.")){
                        hsmwPaymentRecord.setPayType(PayTypeEnum.ALIPAY.getValue());
                    }
                    if (type.startsWith("uac.")){
                        hsmwPaymentRecord.setPayType(PayTypeEnum.UNIPAY.getValue());
                    }
                    HsmwHtnUser user = currentHsmwUserUtils.getCurrentHtnUserInfo();
                    hsmwPaymentRecord.setCompanyId(user.getOwnCompanyId());
                    hsmwPaymentRecord.setUserType(user.getType());
                    hsmwPaymentRecord.setCompanyName(user.getOwnCompanyName());
                    hsmwPaymentRecord.setRechargeUserId(user.getId());
                    hsmwPaymentRecord.setRechargeUserName(user.getName());
                    hsmwPaymentRecord.setCreateUser(user.getId());
                    hsmwPaymentRecordMapper.insert(hsmwPaymentRecord);

                    return new DataResponse(SUCCESS,rspData.get("tn"));
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                    return new DataResponse(respCode);
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
                return new DataResponse(FAIL,"验证签名失败");
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
            return  new DataResponse(FAIL,"未获取到返回报文或返回http状态码非200");
        }

    }


    @SneakyThrows
    @ApiOperation(value = "云闪付支付回调", notes = "云闪付支付回调", produces = "application/json")
    @PostMapping("/unipayBackUrl")
    public void unipayBackUrl(HttpServletRequest req, HttpServletResponse resp) {

        LogUtil.writeLog("BackRcvResponse接收后台通知开始");
        String encoding = req.getParameter(SDKConstants.param_encoding);
        // 获取银联通知服务器发送的后台通知参数
        Map<String, String> reqParam = getAllRequestParam(req);
        LogUtil.printRequestLog(reqParam);

        //重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        if (!AcpService.validate(reqParam, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");

        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            //【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
            String orderId =reqParam.get("orderId"); //获取后台通知的数据，其他字段也可用类似方式获取
            String respCode = reqParam.get("respCode");
            //判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。
            HsmwPaymentRecord hsmwPaymentRecord = hsmwPaymentRecordMapper.selectOne(new LambdaQueryWrapper<HsmwPaymentRecord>().eq(HsmwPaymentRecord::getOrderId, orderId));
            hsmwPaymentRecord.setStatus("1");
            //更新相关的 公司或者搅拌站的  余额信息
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwPaymentRecord.getUserType())){
                HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(hsmwPaymentRecord.getCompanyId());
                if(StringUtils.isNull(plantInfo.getAvailableLimit())){
                    plantInfo.setAvailableLimit(new BigDecimal(0.00));
                }
                BigDecimal bg = new BigDecimal(hsmwPaymentRecord.getPayAmount());
                BigDecimal b =new BigDecimal(100);
                BigDecimal divide = bg.divide(b);
                plantInfo.setAvailableLimit(plantInfo.getAvailableLimit().add(divide));
                hsmwConcretePlantInfoMapper.updateById(plantInfo);
            }
            if(HtnUserTypeEnum.COMPANY.getValue().equals(hsmwPaymentRecord.getUserType())){
                HsmwLeasingCompany  company = hsmwLeasingCompanyMapper.selectById(hsmwPaymentRecord.getCompanyId());
                BigDecimal bg = new BigDecimal(hsmwPaymentRecord.getPayAmount());
                BigDecimal b =new BigDecimal(100);
                BigDecimal divide = bg.divide(b);
                company.setAvailableLimit(company.getAvailableLimit().add(divide));
                hsmwLeasingCompanyMapper.updateById(company);
            }
            hsmwPaymentRecordMapper.updateById(hsmwPaymentRecord);
            resp.getWriter().print("ok");
        }
        LogUtil.writeLog("BackRcvResponse接收后台通知结束");

    }

    public static void main(String[] args) {
        HsmwPaymentRecordController controller = new HsmwPaymentRecordController();
        controller.queryPayInfo("134Z20211227153654013");
    }

    /**
     * 查询支付订单信息
     * @param orderId
     * @return
     * 38a5ede5e512ac03a3d67a0b7e794a1a
     */
    @ApiOperation(value = "查询支付订单", notes = "查询支付订单", produces = "application/json")
    @PostMapping("/queryPayInfo")
    public DataResponse queryPayInfo(String orderId){

        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        MessageDigest messageDigest;
        String encodeStr = "";
        String str ="merOrderId="+orderId+"&mid=89812007392ARVV&msgSrc=WWW.HTN.COM&msgType=query&requestTimestamp="+format+"&signType=SHA256&tid=01599633aaBn6GEBPdiRtDCWNaa5h2RpGbZfbB4FXndAj6mjeC6C2HCn";
        System.err.println(str);
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("merOrderId",orderId);
        paramsMap.put("mid","89812007392ARVV");
        paramsMap.put("msgSrc","WWW.HTN.COM");
        paramsMap.put("msgType","query");
        paramsMap.put("requestTimestamp",format);
        paramsMap.put("signType","SHA256");//
        paramsMap.put("tid","01599633");
        //paramsMap.put("notifyUrl","http://3yzpmxs4.shenzhuo.vip//api/andro/driver/notifyssssssss");
        paramsMap.put("sign",encodeStr);


        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        cn.hutool.json.JSONObject json = JSONUtil.parseFromMap(paramsMap);
        System.err.println(json);
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, json.toString());
        Request request = new Request.Builder()
                .url(clientrUrl)
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            cn.hutool.json.JSONObject responses = JSONUtil.parseObj(response.body().string());
            System.err.println(responses);
            if(responses == null || responses.getStr("errCode").equals("BAD_REQUEST")){
                return new DataResponse(FAIL,"验签失败");
            }
            QueryPayInfo queryPayInfo = JSONUtil.toBean(responses, QueryPayInfo.class);
            return new DataResponse(queryPayInfo);

        } catch (IOException e) {
            e.printStackTrace();
            return new DataResponse(null);
        }

    }




    @SneakyThrows
    @ApiOperation(value = "支付回调", notes = "支付回调", produces = "application/json")
    @PostMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest req, HttpServletResponse resp){

        LogUtil.writeLog("BackRcvResponse接收后台通知开始");
        String merOrderId = req.getParameter("merOrderId");
        HsmwPaymentRecord hsmwPaymentRecord = hsmwPaymentRecordMapper.selectOne(new LambdaQueryWrapper<HsmwPaymentRecord>().eq(HsmwPaymentRecord::getOrderId, merOrderId));
        // 获取银联通知服务器发送的后台通知参数
        Map<String, String> reqParam = getAllRequestParam(req);
        LogUtil.printRequestLog(reqParam);
        Map<String, String> valideData = null;
        if (null != reqParam && !reqParam.isEmpty()) {
            Iterator<Map.Entry<String, String>> it = reqParam.entrySet().iterator();
            valideData = new HashMap<String, String>(reqParam.size());
            while (it.hasNext()) {
                Map.Entry<String, String> e = it.next();
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                valideData.put(key, value);
            }
        }
        String encoding = hsmwPaymentRecord.getSign();
        String status = valideData.get("status");
        if(StringUtils.equals("TRADE_SUCCESS",status)){
            if(!RechargeStatusEnum.SUCCESS.getValue().equals(hsmwPaymentRecord.getStatus())){
                resp.getWriter().print("SUCCESS");
                hsmwPaymentRecord.setStatus("1");
                //更新相关的 公司或者搅拌站的  余额信息
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwPaymentRecord.getUserType())){
                    HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(hsmwPaymentRecord.getCompanyId());
                    if(StringUtils.isNull(plantInfo.getAvailableLimit())){
                        plantInfo.setAvailableLimit(new BigDecimal(0.00));
                    }
                    BigDecimal bg = new BigDecimal(hsmwPaymentRecord.getPayAmount());
                    BigDecimal b =new BigDecimal(100);
                    BigDecimal divide = bg.divide(b);
                    plantInfo.setAvailableLimit(plantInfo.getAvailableLimit().add(divide));
                    hsmwConcretePlantInfoMapper.updateById(plantInfo);
                }
                if(HtnUserTypeEnum.COMPANY.getValue().equals(hsmwPaymentRecord.getUserType())){
                    HsmwLeasingCompany  company = hsmwLeasingCompanyMapper.selectById(hsmwPaymentRecord.getCompanyId());
                    BigDecimal bg = new BigDecimal(hsmwPaymentRecord.getPayAmount());
                    BigDecimal b =new BigDecimal(100);
                    BigDecimal divide = bg.divide(b);
                    company.setAvailableLimit(company.getAvailableLimit().add(divide));
                    hsmwLeasingCompanyMapper.updateById(company);
                }
                hsmwPaymentRecordMapper.updateById(hsmwPaymentRecord);
            }
            resp.getWriter().print("SUCCESS");
        }else {
            resp.getWriter().print("FAILED");

        }
        LogUtil.writeLog("BackRcvResponse接收后台通知结束");
    }

    /**
     * 获取请求参数中所有的信息
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                //System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }


    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}

